package com.qinker.robot.hook.aio;


import com.sky.xposed.common.util.Alog;

import org.smartboot.ioc.Protocol;
import org.smartboot.ioc.transport.NioSession;

import java.nio.ByteBuffer;

/**
 * Created by Irany 2019/10/27 0027 0:10
 */
public class ClientStringProtocol implements Protocol<String> {
    @Override
    public String decode(ByteBuffer readBuffer, NioSession<String> session, boolean eof) {
        int remaining = readBuffer.remaining();
        if (remaining < Integer.BYTES) {
            return null;
        }
        readBuffer.mark();
        //byte转int需要补位
        int length = readBuffer.get() & 0xFF;
        Alog.d("接收到消息长度: " + length);
        if (length > readBuffer.remaining()) {
            readBuffer.reset();
            return null;
        }
        byte[] b = new byte[length];
        readBuffer.get(b);
        readBuffer.mark();
        return new String(b);
    }


    @Override
    public ByteBuffer encode(String msg, NioSession<String> session) {
        byte[] bytes = msg.getBytes();
        ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
        buffer.put(bytes);
        buffer.flip();
        return buffer;
    }
}
